package com.zou.music_downloader;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.inputmethod.InputMethodManager;
import android.widget.SearchView;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.zou.music_downloader.sqlite.MySqliteOpenHelper;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;

/**
 * 主页
 * Created by zou on 2016/3/10.
 */

@EActivity(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {


    @ViewById(R.id.main_tabs)
    TabLayout tabs;

    @ViewById(R.id.main_container)
    ViewPager viewPager;

    private SectionsPagerAdapter myAdapter;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient      client;

    @AfterViews
    void afterView() {
        initView();
    }

    @UiThread
    void initView() {
//        数据库
        MySqliteOpenHelper openHelper = new MySqliteOpenHelper(this);
        openHelper.getWritableDatabase();
        openHelper.close();
        //        初始化viewpager并绑定tabslayout
        myAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(myAdapter);
        tabs.setupWithViewPager(viewPager);

//        直接显示第二页
        viewPager.setCurrentItem(1, false);

//        控制软键盘的显示
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                SearchView         searchView = ((SearchFragment_) myAdapter.list.get(1)).searchview;
                InputMethodManager manager    = (InputMethodManager) getBaseContext().getSystemService(Context.INPUT_METHOD_SERVICE);

// TODO: 2016/3/15 focus与多个fragment的问题，尚需了解
                if (position != 1) {
                    manager.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
                } else if (searchView.hasFocus()) {
//                    判断是否获取焦点来控制软键盘是否弹出
//                    manager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//                    manager.showSoftInput(searchView, 0);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.zou.music_downloader/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.zou.music_downloader/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }



    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public final ArrayList list;

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
            list = new ArrayList();
            list.add(new RecommendFragment_());
            list.add(new SearchFragment_());
            list.add(new HistoryFragment_());

        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
//            return PlaceholderFragment.newInstance(position + 1);
            return (Fragment) list.get(position);
        }


        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "推荐";
                case 1:
                    return "搜索";
                case 2:
                    return "我的下载";
            }
            return null;
        }
    }

}


